import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

task_book_router = APIRouter(prefix="/booking", tags=["预约管理"], dependencies=[Depends(oauth2_scheme)])


class MeetingReservationSearch(PaginationBase):
    # 筛选条件
    fsiteNo: str = Field(..., description="站点编号")
    minTime: str = Field(..., description="开始时间(格式需与数据库存储一致，如'2025-06-26 00:00:00')")
    maxTime: str = Field(..., description="结束时间(格式需与数据库存储一致，如'2025-06-27 23:59:59')")


@task_book_router.get("/list", summary="预约列表查询接口")
def list_task_book(search: MeetingReservationSearch = Query(), db: Session = Depends(get_db)):
    param = {"fsiteNo": search.fsiteNo, "minTime": search.minTime, "maxTime": search.maxTime}
    sql = "select count(1) from meeting "
    sql = sql + " where 1=1"
    sql = sql + " and fsite_no = :fsiteNo "
    sql = sql + " and begintime between :minTime and :maxTime "
    count = db.execute(text(sql), param).scalar()

    param = {"fsiteNo": search.fsiteNo, "minTime": search.minTime, "maxTime": search.maxTime}
    sql = "select id,fsite_no,ftaskno,speaker,room_id,room_name,speaker_id,subject,"
    sql = sql + " begintime,endtime,address,created_id,createdtime,lastupdatetime,"
    sql = sql + " checked_state,checkedtime,memo,meeting_begin_scene,meeting_end_scene,"
    sql = sql + " begin_scene_status,end_scene_status,meeting_type,user_name,signed_number,reason"
    sql = sql + " from meeting "
    sql = sql + " where 1=1"
    sql = sql + " and fsite_no = :fsiteNo "
    sql = sql + " and begintime between :minTime and :maxTime "
    if search.order == "desc":
        sql = sql + " order by  id desc "
    else:
        sql = sql + " order by  id asc "
    sql = sql + " limit :limit offset :offset "
    param["limit"] = search.limit
    param["offset"] = search.offset
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['id'] = data[key][0]
        d1['fsiteno'] = data[key][1]
        d1['ftaskno'] = data[key][2]
        d1['speaker'] = data[key][3]
        d1['roomid'] = data[key][4]
        d1['roomname'] = data[key][5]
        d1['speakerid'] = data[key][6]
        d1['subject'] = data[key][7]
        d1['begintime'] = data[key][8]
        d1['endtime'] = data[key][9]
        d1['address'] = data[key][10]
        d1['createdid'] = data[key][11]
        d1['createdtime'] = data[key][12]
        d1['lastupdatetime'] = data[key][13]
        d1['checkedstate'] = data[key][14]
        d1['checkedtime'] = data[key][15]
        d1['memo'] = data[key][16]
        d1['meetingbeginscene'] = data[key][17]
        d1['meetingendscene'] = data[key][18]
        d1['beginscenestatus'] = data[key][19]
        d1['endscenestatus'] = data[key][20]
        d1['meetingtype'] = data[key][21]
        d1['username'] = data[key][22]
        d1['signednumber'] = data[key][23]
        d1['reason'] = data[key][24]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class LabReservationUpdate(BaseModel):
    """实验室预约驳回请求参数"""
    meetingId: str = Field(..., description="预约ID")
    type: int = Field(..., description="驳回类型")
    reason: str = Field("", description="驳回原因")


@task_book_router.post("/status", summary="实验室预约驳回接口")
def list_task_router(update: LabReservationUpdate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "update meeting set meeting_type= :type , reason= :reason  where id= :meetingId "
            db.execute(text(sql), {
                "type": update.type,
                "meetingId": update.id,
                "reason": update.reason
            })
            return BaseResponse.success()

    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
